//
//  DWRequest.swift
//  DWSwift
//
//  Created by GDL on 2025/6/23.
//

import Foundation
import DWCoreLib
import Moya

public class DWNetworkManager {
    
    public static let shared = DWNetworkManager.init()

    private let provider: MoyaProvider<MultiTarget>
    
    public init() {
        let requestClosure = { (endpoint: Endpoint, done: @escaping MoyaProvider.RequestResultClosure) in
            do {
                var request = try endpoint.urlRequest()
                request.timeoutInterval = NetworkConfig.shared.timeout // 全局超时
                done(.success(request))
            } catch {
                done(.failure(.underlying(error, nil)))
            }
        }
        // 集成全局插件
        provider = MoyaProvider<MultiTarget>(
            requestClosure: requestClosure,
            plugins: NetworkConfig.shared.plugins
        )
    }
    
    // 支持 async/await 的请求方法
    public func request<T: Decodable>(_ builder: RequestBuilder) async throws -> T {
        let target = MultiTarget(builder.build())
        return try await withCheckedThrowingContinuation {continuation in
//            guard let self = self else {
//                 continuation.resume(throwing: CancellationError()) // 若 self 已释放，取消任务
//                 return
//             }
//            self.loadStateManager.startLoading()
            provider.request(target) { result in
//                self.loadStateManager.stopLoading()
                switch result {
                case .success(let response):
                    do {
                        let data = try response.map(T.self)
                        continuation.resume(returning: data)
                    } catch let error {
                        continuation.resume(throwing: error)
                    }
                case .failure(let error):
                    continuation.resume(throwing: error)
                }
            }
        }
    }
    
    // MARK: GET
    static func GET<T:Decodable> (path:String,params: [String: Any]?) async throws -> T{
        var builder:RequestBuilder = RequestBuilder(path: path,method:.get)
        if let dict = params, !dict.isEmpty {
            builder = builder.setTask(.requestParameters(parameters: dict, encoding: URLEncoding.default))
        }
        // 调用底层 request 方法
        return try await DWNetworkManager.shared.request(builder)
    }
    
    // MARK: POST
    static func POST<T:Decodable> (path:String,params: [String: Any]?) async throws -> T{
        var builder:RequestBuilder = RequestBuilder(path: path,method:.post)
        if let dict = params, !dict.isEmpty {
            builder = builder.setTask(.requestParameters(parameters: dict, encoding: URLEncoding.default))
        }
        // 调用底层 request 方法
        return try await DWNetworkManager.shared.request(builder)
    }
}
